from langchain.text_splitter import CharacterTextSplitter,MarkdownTextSplitter,RecursiveCharacterTextSplitter
# from langchain.document_loaders import UnstructuredFileLoader,UnstructuredMarkdownLoader,UnstructuredWordDocumentLoader
import os
from fastapi import APIRouter, Query, UploadFile, File,Form,Body
from xingchen import Configuration, CharacterPermissionConfig,ApiClient, ChatApiSub, ChatReqParams,CharacterUpdateDTO, CharacterKey, Message, UserProfile, ModelParameters,ChatContext,CharacterCreateDTO,CharacterApiSub
import time

from typing import Optional
from pydantic import BaseModel
from embeddingDB import pgDB
from typing import Dict, Any
 
router = APIRouter(
    prefix= "/soundBank",
    tags= ["soundBankRouter"],
    responses= {404: {"description": "Not found path knowledge"}}
)



class userMessage(BaseModel):
    sound_id: Optional[str] = ""
    nick_name: Optional[str] = ""
    user_id: Optional[str] = ""
    content: Optional[str] = ""

from fastapi.responses import StreamingResponse
@router.post("/tts")
async def tts(msg:userMessage):
    return ""
    # return StreamingResponse(generate_text_from_xingchen(msg), media_type="text/plain")
# test_chat_async()
# test_chat_sync()

# work_dir = "."lm-qbcQwj0A9CKMEBu4YkVe6Q==

# 转换函数
def snake_to_camel(s: str) -> str:
    parts = s.split('_')
    return parts[0].lower() + ''.join(x.capitalize() for x in parts[1:])
 
# 递归转换字典键的函数
def convert_keys_to_camel(d: Dict[str, Any]) -> Dict[str, Any]:
    if isinstance(d, dict):
        return {snake_to_camel(k): convert_keys_to_camel(v) for k, v in d.items()}
    elif isinstance(d, list):
        return [convert_keys_to_camel(item) for item in d]
    else:
        return d
    
from datetime import datetime
class Sound(BaseModel):
    id:Optional[int] = 0
    sound_id: Optional[str] = ""
    name: Optional[str] = ""
    introduction: Optional[str] = ""
    create_time: Optional[datetime] = ""
    update_time: Optional[datetime] = ""
    
    
    
@router.post("/createSound")
def createSound(params:Sound):
    rs = {"code":200,"msg":"创建成功","data":{}}
    name = params.name
    print(params)
    # 角色管理准备部分已省略

    # result
    
    sql = '''
    INSERT INTO sound(name,sound_id,introduction)
    VALUES('{}','{}','{}','{}','{}','{}','{}','{}')
    '''.format(name,result.data.sound_id,params.introduction)
    db = pgDB()
    db.modify(sql)
    db.close()
    
    
    # k = embeddingDB.VectorDB()
    # k.getCollection(title)
    # print()
    rs["data"] = result.data
    return rs


@router.post("/updateSound")
def updateSound(params:Sound):
    rs = {"code":200,"msg":"创建成功","data":{}}
    # name = params.name
    print(params)
    # 角色管理准备部分已省略

    
    sql = '''
    UPDATE sound
    SET name='{}',introduction='{}'
    WHERE id='{}'
    
    '''.format(params.name,params.introduction,params.id)
    db = pgDB()
    print(sql)
    db.modify(sql)
    db.close()
    
    
    # k = embeddingDB.VectorDB()
    # k.getCollection(title)
    # print()
    rs["data"] = "修改成功"
    return rs

    
@router.post("/getSoundList")
def getSoundList(params:Sound):
    rs = {"code":200,"msg":"创建成功","data":{}}
    # title = params.title
    # print(params)
    
    sql = '''
    SELECT *
    FROM sound
    '''
    db = pgDB()
    data = db.select(sql)
    db.close()
    
    # data = [ convert_keys_to_camel(Sound(**d).dict()) for d in data]
    # data = data.dict()  # 将 Pydantic 模型转换为字典
    # data = convert_keys_to_camel(data)  # 将字典键转换为驼峰命名
    
    rs["data"] = data
    print(">>",rs["data"])
    return rs
    
@router.post("/deleteSound")
def deleteSound(params:Sound):
    rs = {"code":200,"msg":"删除成功","data":{}}
    print(params)
    sql = '''
    DELETE FROM sound 
    WHERE id = '{}'
    '''.format(params.id)
    db = pgDB()
    data = db.modify(sql)
    rs["data"] = {}
    db.close()
    
    # k.delSound(params.title)
    
    return rs
    
@router.post("/getSoundInfo")
def getSoundInfo(params:Sound):
    rs = {"code":200,"msg":"查询成功","data":{}}
    # title = params.title
    # print(params)
    
    sql = '''
    SELECT * 
    FROM sound
    WHERE id = '{}'
    '''.format(params.id)
    print(sql)
    db = pgDB()
    
    data = db.select(sql)[0]
    data = Sound(**data)
    # data = data.dict()  # 将 Pydantic 模型转换为字典
    # data = convert_keys_to_camel(data)  # 将字典键转换为驼峰命名
    
    # SoundInfo = xingchenCharacterAPI.character_details(sound_id=data.sound_id)
    # print(SoundInfo.data)
    db.close()
    
    # rs["data"] = data
    # db.close()
    # print(">>",rs["data"])
    # print()
    # try:
    #     fileList = [{"fileName":f } for f in os.listdir("./uploadFiles/{}".format(params.id))]
    # except:
    #     fileList=[]
    # print(kList)
    # k.delSound(params.title)
    rs["data"] = data
    return rs
    
    
